package org.jeecg.modules.gis.util.mybatis;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.gis.mapper.DataManagerMapper;
import org.jeecg.modules.gis.util.GisDbUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

public abstract class GisBaseServiceImpl implements IGisBaseService {

    @Autowired
    protected GisDbUtil gisDbUtil;
    @Autowired
    GeoJsonUtil geoJsonUtil;
    @Autowired
    protected GisDialectRegistry dialectRegistry;
    @Autowired
    private GisBaseMapper gisBaseMapper;

    @Override
    public JSONObject getFeatureCollection(String tableName) throws Exception {
        String dbType = gisDbUtil.getDbType(); // 这里调用自己的工具类获取数据库类型
        List<Map<String, Object>> list = gisBaseMapper.getFeatureCollection(gisDbUtil.formatTableName(dbType, tableName));
        return geoJsonUtil.listMapToFeatureCollection(list, dbType);
    }

    @Override
    public File exportShpZip(String tableName) throws Exception {
        String dbType = gisDbUtil.getDbType(); // 这里调用自己的工具类获取数据库类型
        List<Map<String, Object>> list = gisBaseMapper.getFeatureCollection(tableName);
        JSONObject geoJson = geoJsonUtil.listMapToFeatureCollection(list, dbType);
        File zip = geoJsonUtil.exportGeoJsonToShpAndZip(geoJson.toJSONString(), tableName);
        return zip;
    }

    public byte[] exportAsGeoJson(String tableName) throws Exception {
        // 获取数据库类型（用于属性字段处理）
        String dbType = gisDbUtil.getDbType();

        // 从数据库获取数据（Feature 列表）
        List<Map<String, Object>> list = gisBaseMapper.getFeatureCollection(tableName);

        // 构造 GeoJSON 对象
        JSONObject geoJson = geoJsonUtil.listMapToFeatureCollection(list, dbType);

        // 临时目录路径
        String tmpDir = System.getProperty("java.io.tmpdir") + "/gisworkspace/exportdata";
        File dir = new File(tmpDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 构造目标文件路径
        File geoJsonFile = new File(dir, tableName + ".geojson");

        // 写入 GeoJSON 内容到文件
        try (FileWriter writer = new FileWriter(geoJsonFile)) {
            writer.write(geoJson.toJSONString());
        }

        // 读取为字节数组返回
        return Files.readAllBytes(geoJsonFile.toPath());
    }

}
